//
//  AddAddressViewController.m
//  1243
//
//  Created by 王 on 16/5/17.
//  Copyright © 2016年 1243. All rights reserved.
//

#import "AddAddressViewController.h"
#import "TextFieldCell.h"
#import "DetailCell.h"
#import "GPDateView.h"
#import "NetWorkTools.h"

@interface AddAddressViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UIAlertViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, assign, getter=isDefault) BOOL Default;

@property (nonatomic, strong) NSString *name;

@property (nonatomic, strong) NSString *phoneNum;

@property (nonatomic, strong) NSString *postCode;

@property (nonatomic, strong) NSString *detailAddress;

@property (nonatomic, strong) NSString *province;

@property (nonatomic, strong) NSString *city;

@property (nonatomic, strong) NSString *countory;

@property (nonatomic, strong) UITextField *nameTextField;

@property (nonatomic, strong) UITextField *phoneNumTextField;

@property (nonatomic, strong) UITextField *postCodeTextField;

@property (nonatomic, strong) UITextField *detailAddressTextField;

@property (nonatomic, assign) int number;

@property(nonatomic,assign,getter=isDeleteDefault)BOOL deleteDefault;

@end

#define Key_DistrictSelectProvince          @"DistrictSelectProvince"
#define Key_DistrictSelectProvinceCode      @"DistrictSelectProvinceCode"
#define Key_DistrictSelectProvinceSubCode   @"DistrictSelectProvinceSubCode"
#define Key_DistrictSelectProvinceSub       @"DistrictSelectProvinceSub"
#define Key_DistrictSelectCityCode          @"DistrictSelectCityCode"
#define Key_DistrictSelectCity              @"DistrictSelectCity"

@implementation AddAddressViewController

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStyleGrouped];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    if (self.num == 0) {
        self.title = @"添加新地址";
    } else {
        self.title = @"修改地址";
    }
    
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImage:nil highImage:nil target:self action:@selector(rightItem) forControlEvents:UIControlEventTouchUpInside title:@"保存"];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"TextFieldCell" bundle:nil] forCellReuseIdentifier:@"TextFieldCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DetailCell" bundle:nil] forCellReuseIdentifier:@"DetailCell"];
    [self.nameTextField becomeFirstResponder];
    
    //监听键盘的弹出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    self.deleteDefault = NO;
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    if (self.num == 1) {
        self.Default = [self.dic[@"IsDefault"] isEqual:@(0)] ? NO : YES;
        self.name = self.dic[@"ContactName"];
        self.phoneNum = self.dic[@"ContactPhone"];
        self.postCode = self.dic[@"ContactPostCode"];
        self.detailAddress = self.dic[@"Address"];
        self.province = self.dic[@"Province"];
        self.city = self.dic[@"City"];
        self.countory = self.dic[@"Countory"];
        
    } else {
        self.Default = NO;
    }
}

- (void)rightItem {
    if (self.num == 1) {
        [self changeAddress];
    } else {
        [self addAddress];
    }
    
}

#pragma mark - 键盘的Frame改变的时候调用
- (void)keyboardFrameChange:(NSNotification *)note {
    
    CGFloat durtion = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    
    //获取键盘的frame
    CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    if (frame.origin.y == HEIGHT) {//没有弹出键盘
        [UIView animateWithDuration:durtion animations:^{
            self.tableView.height = HEIGHT;
        }];
    } else {//弹出键盘
        [UIView animateWithDuration:durtion animations:^{
            //工具条往上移动271
            self.tableView.height = HEIGHT - frame.size.height;
        }];
    }
    //    WSYLog(@"%@", note.userInfo);
}

- (void)changeAddress {
    
    if (self.nameTextField.text.length == 0 || self.phoneNumTextField.text.length == 0|| self.detailAddressTextField.text.length == 0 || self.postCodeTextField.text.length == 0 || self.province.length == 0) {
        
        
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请填写完整信息" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alview.tag = 123306;
        [alview show];
        
        
    }else{
    
    NSDictionary *userData = [ReadLoginData readLoginData];
    
    NSString *userId = [userData objectForKey:@"Number"];
    
    NSDictionary *params = @{
                             @"Id":[self.dic objectForKey:@"Id"],
                             @"UserId":userId,
                             @"Province":self.province,
                             @"City":self.city,
                             @"Countory":self.countory,
                             @"Address":self.detailAddress,
                             @"ContactName":self.name,
                             @"ContactPhone":self.phoneNum,
                             @"ContactMobile":@"",
                             @"ContactPostCode":self.postCode,
                             @"AddTime":self.dic[@"AddTime"],
                             @"IsDefault":[NSString stringWithFormat:@"%@",self.isDefault ? @"1" : @"0"]
                             };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"UPDATEEXPRESS" completeBlock:^(id object) {
        
        NSInteger Id = [[object objectForKey:@"Id"] integerValue];
        
        if (Id == 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"修改地址成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            alert.tag = 10010;
            
            [alert show];
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"修改地址失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            
            [alert show];
        }
    }];
    }
}

- (void)addAddress {
    if (self.nameTextField.text.length == 0 || self.phoneNumTextField.text.length == 0|| self.detailAddressTextField.text.length == 0 || self.postCodeTextField.text.length == 0 || self.province.length == 0) {
        
        
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请填写完整信息" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alview.tag = 123306;
        [alview show];
        
        
    }else{
        
        NSDictionary *userData = [ReadLoginData readLoginData];
        
        NSString *userId = [userData objectForKey:@"Number"];
        
        NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm:ss"];
        NSString *currentTime = [formatter stringFromDate:[NSDate date]];
        
        NSDictionary *param = @{
                                @"Id":@"0",
                                @"UserId":userId,
                                @"Province":[NSString stringWithFormat:@"%@", self.province],
                                @"City":[NSString stringWithFormat:@"%@", self.city],
                                @"Countory":[NSString stringWithFormat:@"%@",self.countory],
                                @"Address":[NSString stringWithFormat:@"%@", self.detailAddress],
                                @"ContactName":[NSString stringWithFormat:@"%@", self.name],
                                @"ContactPhone":[NSString stringWithFormat:@"%@", self.phoneNum],
                                @"ContactMobile":@"",
                                @"ContactPostCode":self.postCode,
                                @"AddTime":currentTime,
                                @"IsDefault":[NSString stringWithFormat:@"%@",self.isDefault ? @"1" : @"0"]
                                };
        
        [[NetWorkTools sharedNetWorkTools] objectWithURLDict:param AndMenthodName:@"EXPRESSADDRESS" completeBlock:^(id object) {
            NSLog(@"%@",object);
            
            NSInteger responceNumber = [[object objectForKey:@"Id"] integerValue];
            
            if (responceNumber == 0) {
                
                NSString *message = [NSString stringWithFormat:@"%@",[object objectForKey:@"Message"]];
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                alert.tag = 10010;
                [alert show];
            } else {
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:object[@"Message"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                
                alert.tag = 10011;
                
                [alert show];
                
            }
        }];
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark UITableView DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 5;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:13];
    }
    if (indexPath.section == 0) {
        if (indexPath.row < 3) {
            TextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TextFieldCell" forIndexPath:indexPath];
            cell.TextField.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (indexPath.row == 1) {
                self.phoneNumTextField = cell.TextField;
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChange2) name:UITextFieldTextDidChangeNotification object:cell.TextField];
                if (self.num == 1) {
                    cell.TextField.text = self.dic[@"ContactPhone"];
                }
            }
            if (indexPath.row == 0) {
                cell.TextLabel.text = @"收货人";
                self.nameTextField = cell.TextField;
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChange1) name:UITextFieldTextDidChangeNotification object:cell.TextField];
                if (self.num == 1) {
                    cell.TextField.text = self.dic[@"ContactName"];
                }
            }
            if (indexPath.row == 2) {
                cell.TextLabel.text = @"邮编";
                self.postCodeTextField = cell.TextField;
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChange4) name:UITextFieldTextDidChangeNotification object:cell.TextField];
                if (self.num == 1) {
                    
                    if ([self.dic[@"ContactPostCode"] isKindOfClass:[NSNull class]]) {
                        NSLog(@"sssssssssss");
                        cell.TextField.text = @"";
                    }else{
                         cell.TextField.text = self.dic[@"ContactPostCode"];
                    }
                    
                   
                }
            }
            
            return cell;
        } else if (indexPath.row == 3) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.text = @"所在地区";
            cell.detailTextLabel.text = @"请选择";
            if (self.num == 1) {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@%@", self.dic[@"Province"], self.dic[@"City"], self.dic[@"Countory"]];
            }
        } else {
            DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailCell" forIndexPath:indexPath];
            cell.TextField.delegate = self;
            self.detailAddressTextField = cell.TextField;
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChange3) name:UITextFieldTextDidChangeNotification object:cell.TextField];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (self.num == 1) {
                cell.TextField.text = self.dic[@"Address"];
            }
            return cell;
        }
    } else {
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        if (self.num == 1) {
            cell.textLabel.text = @"删除地址";
            cell.textLabel.textColor = [UIColor orangeColor];
        } else {
            cell.textLabel.text = @"设为默认";
            if (self.isDefault) {
                cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_mr_h"]];
            } else {
                cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_mr_n"]];
            }
        }
    }
    
    return cell;
}

#pragma mark - UITableView Delegate 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 4) {
            return 120;
        }
    }
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 20;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 3) {
            [self ResignFirstResponder];
            [self pickerView:indexPath];
        }
    } else {
        if (self.num == 1) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"确定要删除该地址吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = 10000;
            [alert show];
        } else {
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            self.Default = !self.Default;
            if (self.isDefault) {
                cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_mr_h"]];
                if (self.arrM.count != 0) {
                    for (int i = 0; i < self.arrM.count; i ++) {
                        int IsDefault = [self.arrM[i][@"IsDefault"] intValue];
                        if (IsDefault == 1 ) {
                            self.number = i;
                            [self.arrM[i] setValue:@(0) forKey:@"IsDefault"];
                            [self updateAddressData:self.arrM[i]];
                            return;
                        }
                    }
                }
                
            } else {
                cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_mr_n"]];
                if (self.arrM.count != 0) {
                    [self.arrM[self.number] setValue:@(1) forKey:@"IsDefault"];
                    [self updateAddressData:self.arrM[self.number]];
                }
            }
        }
    }
}

#pragma mark >>>>>>> 更新地址
- (void)updateAddressData:(NSDictionary *)dic
{
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:dic AndMenthodName:@"UPDATEEXPRESS" completeBlock:^(id object) {
        
    }];
}

- (void)pickerView:(NSIndexPath *)indexPath{
    
    GPDateView * dateView = [[GPDateView alloc] initWithFrame:CGRectMake(0, HEIGHT-250, WIDTH, 250) Data:nil];
    
    [dateView showPickerView];
    
    dateView.ActionDistrictViewSelectBlock = ^(NSString *desStr,NSDictionary *selectDistrictDict){
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@%@", [selectDistrictDict objectForKey:Key_DistrictSelectProvince], [selectDistrictDict objectForKey:Key_DistrictSelectCity], [selectDistrictDict objectForKey:Key_DistrictSelectProvinceSub]];
        
        self.province = [selectDistrictDict objectForKey:Key_DistrictSelectProvince];
        self.city = [selectDistrictDict objectForKey:Key_DistrictSelectCity];
        self.countory = [selectDistrictDict objectForKey:Key_DistrictSelectProvinceSub];
        
    };
}

- (void)didChange1{
    
    self.name = self.nameTextField.text;
    NSLog(@"%@",self.nameTextField.text);
}
- (void)didChange2 {
    self.phoneNum = self.phoneNumTextField.text;
    NSLog(@"%@",self.phoneNumTextField.text);
}
- (void)didChange3 {
    self.detailAddress = self.detailAddressTextField.text;
    NSLog(@"%@",self.detailAddressTextField.text);
}
- (void)didChange4 {
    self.postCode = self.postCodeTextField.text;
    NSLog(@"%@",self.postCodeTextField.text);
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1 && alertView.tag == 10000) {
        if ([self.dic[@"IsDefault"] isEqual:@(1)]) {
            self.deleteDefault = YES;
        } else {
            self.deleteDefault = NO;
        }
        [self deleteAddressData:self.dic];
        
    }
    
    if (alertView.tag == 10010) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark >>>>>>> 删除地址
- (void)deleteAddressData:(NSDictionary *)dict
{
    NSDictionary *userData = [ReadLoginData readLoginData];
    
    NSString *userId = [userData objectForKey:@"Number"];
    
    NSDictionary *params = @{
                             //                             @"UserId":@"1"
                             @"UserId":userId,
                             @"AddressId":dict[@"Id"]
                             };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"DELETEADDRESS" completeBlock:^(id object) {
        NSLog(@"%@",object);
        if ([object[@"Id"] isEqual:@(0)]) {
            if (self.isDeleteDefault) {
                [self loadUserAddressData];
            }
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    }];
}

#pragma mark>>>>> 获取地址
- (void)loadUserAddressData {
    
    NSDictionary *userData = [ReadLoginData readLoginData];
    
    NSString *userId = [userData objectForKey:@"Number"];
    
    NSDictionary *params = @{
                             //
                             @"UserId":userId
                             };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"EXPRESSQUERY" completeBlock:^(id object) {
        //        NSLog(@"%@",object);
        
        NSLog(@"%@",[object objectForKey:@"BackData"]);
        NSString *string = [object objectForKey:@"BackData"];
        NSArray *arr = [NetWorkTools arrayWithJsonString:string];
        NSMutableArray *arrM = [NSMutableArray array];
        [arrM addObjectsFromArray:arr];
        if (arrM.count != 0) {
            [arrM[0] setValue:@(1) forKey:@"IsDefault"];
            [self updateAddressData:arrM[0]];
        }
    }];
}


- (void)ResignFirstResponder {
    
    [self.nameTextField resignFirstResponder];
    [self.phoneNumTextField resignFirstResponder];
    [self.postCodeTextField resignFirstResponder];
    [self.detailAddressTextField resignFirstResponder];
}

@end
